﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using NTTDATA.BEENChina.ResultCertification.Config;
using NTTDATA.BEENChina.ResultCertification.Util;
using NTTDATA.BEENChina.ResultCertification.model;

namespace NTTDATA.BEENChina.ResultCertification.Checker.Text
{
    
    [Serializable]
    [VerfityAttribute(Id = "VerfityTX0100", Name = "应用特定规则对文字列进行模糊检证", CategoryType = EnumCategoryType.文字列, Model = true)]
    public class VerfityTx0100 : VerfityOneResult
    {

        [Category("应用的规则"), Description("应用的检验规则（可多选）")]
        public EnumTextNameType SpeicficRule 
        {
            get { return this._speicficRult; }
            set { this._speicficRult = value; }
        }

        private EnumTextNameType _speicficRult = EnumTextNameType.无;

        
        public override bool CheckResult(List<List<string>> result, string entryCommon)
        {
            bool bresult = false;
            if (entryCommon.Equals("30"))
            {
                return false;
            }

            if (result == null)
            {
                return false;
            }

            var entryText = new StringBuilder();

            result.ForEach(row =>
                               {
                                   if (entryText.Length>0)
                                       entryText.Append(@"\\");
                                   entryText.Append(string.Join(@"\\", row));
                               }); 
                 
            //所有行合并到一起检验
            bresult = CheckErrorCell(entryText.ToString());

            //bresult = result.SelectMany(o => o).Any(CheckErrorCell); 


            if (bresult)
            {
                System.Console.WriteLine("VerfityT0100");
            }

            return bresult;
        }

      
        
        private bool CheckErrorCell(string colResult)
        {
            bool bresult = false;

            var rult = (EnumTextType) (_speicficRult);

            var textItems = Logic.JaTexts.GetInstance().GetJaTextItems(rult);
            //bresult = textItems.AsParallel().OrderBy(t => t.ID).Any(t => CheckSimilarity(colResult, t));

            //去掉 AsParallel()
            if (textItems != null) 
                bresult = textItems.OrderBy(t => t.ID).Any(t => CheckSimilarity(colResult, t));

            return bresult;
        }

        private bool CheckSimilarity(string colResult, JaTextItem jaItem)
        {
            var dbName = Util.CharacterChange.ToDbc(jaItem.Name);

            //如果不想区分大小写
            //.ToLower();
            //colResult = colResult.ToLower();
            decimal checkSimilarity = jaItem.MaxSimilarity;

            //如果交集是0 没有重合的字符 
            if (string.IsNullOrEmpty(colResult) || 
                string.IsNullOrEmpty(dbName) || 
                colResult.Contains(dbName) ||
        
                dbName.ToCharArray().Any(colResult.Contains) == false
                /*colResult.ToCharArray().Intersect(dbName.ToCharArray()).Count().Equals(0)*/
                )
            {
                return false;
            }
 
            //decimal maxSimilarity = -1;



            /*for (int i = 0; i + dbName.Length <= colResult.Length; i++)
            {
                string resultpart = colResult.Substring(i,Math.Min( colResult.Length - i , dbName.Length));
                decimal similarity = CompareString.LevenshteinDistancePercent(resultpart, dbName);
                maxSimilarity = similarity > maxSimilarity ? similarity : maxSimilarity;


                 /*if (jaItem.ID.Equals("SSM0099"))
                      Console.WriteLine(resultpart + ":" + dbName + ":" + maxSimilarity);  #1#
            }*/

  

            List<string> resultParts = null; 


/*
            for (int i = 0; i + dbName.Length <= colResult.Length; i++)
            {
                string resultpart = colResult.Substring(i, Math.Min(colResult.Length - i, dbName.Length));

                if (IgronString(resultpart))
                    continue;

                if (resultpart.ToCharArray().Count(dbName.Contains) >= (int)(dbName.Length * jaItem.MaxSimilarity / 100)) 
                 {
                    //手术名 医院名
                    //检证内容的起始字符和结束字符不参与检证
                    if (jaItem.NameType == EnumTextType.SSM || jaItem.NameType == EnumTextType.YYM)
                    {

                        if (String.Compare(resultpart, 0, dbName, 0, 1) != 0 ||
                            String.Compare(resultpart, resultpart.Length - 1, dbName, dbName.Length - 1, 1) != 0)
                        {
                            continue;
                        }
                    }
                    
                    if (resultParts == null)
                    {
                        resultParts = new List<string>();
                    }


                    resultParts.Add(resultpart);   
                    
                     
                 }
            }
*/

           /* if (jaItem.ID.Equals("BM0278"))
                Console.WriteLine(jaItem.Name);*/


            //
            int starIndex = 0;
            int keyIndex = -1;
            do
            {

                keyIndex = colResult.IndexOfAny(dbName.ToCharArray(), starIndex );

                if (keyIndex.Equals(-1))
                    break;

            
                string tempVal = string.Empty;

                if (keyIndex + dbName.Length <= colResult.Length)
                {
                     tempVal = colResult.Substring(keyIndex, dbName.Length);
                }
                else
                {
                    tempVal = colResult.Substring(keyIndex);
                }


                //追加限定条件
                //当截取的录入内容片段比检索词位数少时不抽出
                if (!String.IsNullOrEmpty( tempVal ) 
                    // && tempVal.Length .Equals(dbName.Length)
                    )
                {
                   /* if (IgronString(tempVal))
                        continue;*/

                    if (tempVal.ToCharArray().Count(dbName.Contains) >= (int)(dbName.Length * jaItem.MaxSimilarity / 100))
                    {
                        //手术名 医院名
                        //检证内容的起始字符和结束字符不参与检证
                        if (jaItem.NameType == EnumTextType.SSM || jaItem.NameType == EnumTextType.YYM)
                        {

                            if (String.Compare(tempVal, 0, dbName, 0, 1) != 0 ||
                                String.Compare(tempVal, tempVal.Length - 1, dbName, dbName.Length - 1, 1) != 0)
                            {
                               // continue;
                                goto End;
                            }
                        }

                        if (resultParts == null)
                        {
                            resultParts = new List<string>();
                        }


                        resultParts.Add(tempVal);


                    } 

                    
                }
                
                End:
                starIndex = keyIndex + 1;

            } while (keyIndex < 0 || starIndex < colResult.Length);

            //

            bool resultsimilarity = false;

            decimal similarity = 0;

            if (resultParts != null)
            {
                var compareString = new CompareString();

                resultsimilarity = resultParts.
                                    AsParallel().
                                    Any(t =>
                                        {
                                              similarity =
                                                compareString.LevenshteinDistancePercent(t,dbName);
                                            bool bcheck = (similarity >= checkSimilarity) && !similarity.Equals(100);

                                            if (bcheck)
                                            {
                                                /*//录入内容/库里内容/ID（不用看）/相似度/检出标准
                                                ChildImageObject.Reason.Reason =
                                                    string.Format("{0} / {1}  / {2} / {3} / {4}", t,
                                                     dbName, jaItem.ID, similarity,jaItem.MaxSimilarity);

                                                //错误提示信息
                                                //ChildImageObject.Reason.ErrorRanage = dbName;*/

                                                
                                                SetErrorRange(dbName);
                                            }

                                            return bcheck;
                                        });

            }

           /* if (resultsimilarity
                || jaItem.ID.Equals("BM0278")
            )
            {
                Console.WriteLine(jaItem.ID + ":" + dbName + ":" + similarity);  
                  Console.WriteLine(ChildImageObject.Reason.Reason); 
            }*/
            return resultsimilarity;

        }


       /* private bool IgronString(string entry)
        {
            var igronChar = new string[] { @"\", "、", "。", ""," " };
            return igronChar.AsParallel().Any(t => entry.StartsWith(t) || entry.EndsWith(t));
        }*/

    }
}
